<template>
  <div class="form">
    <el-form :model="todolist" label-width="auto" inline>
      <el-form-item label="请设置标签大小：">
      </el-form-item>
      <el-form-item label="宽" width="30px">
        <el-input v-model="todolist.widthPx" />
      </el-form-item>
      <el-form-item label="高">
        <el-input v-model="todolist.heightPx" />
      </el-form-item>
      <el-form-item>
        <el-checkbox v-model="todolist.checked1" label="锁定比例" size="large" />
      </el-form-item>
    </el-form>
  </div>
  <div>
    需要打印的信息推拽：
    <transition-group name="drag" class="list" tag="ul" style="display: flex">
      <div v-for="(item, index) in todolist.names" :key="item.label" draggable
        :class="['list-item', { 'is-dragover': index === dragOverIndex }]" @dragstart="dragStart(item, index)"
        @mousedown="dragStart(item, index)" @dragover.prevent="dragOver(index)" @dragend="dragEnd()">
        {{ item.label }}
      </div>
    </transition-group>
  </div>

  <div class="one">
    <div id="drop" ref="dropArea"
      :style="{ width: parseInt(todolist.widthPx * 4.68) + 'px', height: parseInt(todolist.heightPx * 4.68) + 'px', border: '3px solid black', backgroundColor: 'pink', position: 'relative', overflow: 'hidden' }"
      @dragover.prevent="allowDrop" @drop="dropItem">
      <table ref="tableDrop" @dragstart="tableContent(todolist.names, index)" draggable="true"
        :style="{ position: 'absolute', left: tableX + 'px', top: tableY + 'px', width: '702px' }">
        <thead>
          <tr>
            <th v-for="(item, index) in tableDivContent" :key="index">{{ item.label }}</th>
          </tr>
        </thead>
        <tbody>
          <tr>
          </tr>
        </tbody>
      </table>
    </div>
    <!-- <img src='http://yitaoweb.sc.kuaidi600.com/expressMoban.png' />
    <img src='http://yitaoweb.sc.kuaidi600.com/xiao.png' />
    <img src='http://yitaoweb.sc.kuaidi600.com/expressMoban.png' /> -->
  </div>
  <button @click="sets">保存配置</button>

</template>

<script setup>
import { ref, onBeforeMount, onBeforeUpdate, watch, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { sysPrintTemplateSetGetSysPrintTemplateSetDetail, sysPrintTemplateSetUpdate } from '@/api/index'
const route = useRoute()
onBeforeMount(() => {
  getDetile(route.query.ID)
})
onMounted(() => {

})
const IDs = ref('')
watch(IDs, (e, a) => {
  getDetile(route.query.ID)
  dropItem()
})

onBeforeUpdate(() => {
  IDs.value = route.query.ID
})
const getDetile = (id) => {
  sysPrintTemplateSetGetSysPrintTemplateSetDetail({ id: id }).then(res => {
    const { data: { data } } = res
    orderId.value = data.orderId
    todolist.value.widthPx = data.wide
    todolist.value.heightPx = data.high
    tableX.value = data.tableLeft
    tableY.value = data.tableTop
    todolist.value.names = data.labelJson ? JSON.parse(data.labelJson) : todolist.value.names
  })
}
const orderId = ref(null)
const todolist = ref(
  {
    checked1: false,
    widthPx: '',
    heightPx: '',
    names: [
      { label: '条形码', top: '', left: '', isOr: false, name: 'waybillCode', width: '65', height: '20', id: '1', barCodeLabel: false },
      { label: ' 货物区域 ', top: '', left: '', isOr: false, name: 'areaShop', width: '65', height: '', id: '2', barCodeLabel: true },
      { label: '库位信息', top: '', left: '', isOr: false, name: 'storagelocation', width: '65', height: '', id: '3', barCodeLabel: true },
      { label: '数量', top: '', left: '', isOr: false, name: 'num', width: '65', height: '', id: '4', barCodeLabel: true },
      { label: '入库批次号', top: '', left: '', isOr: false, name: 'batchNum', width: '65', height: '', id: '5', barCodeLabel: true },
      { label: 'SKU信息', top: '', left: '', isOr: false, name: 'skuInfo', width: '65', height: '', id: '6', barCodeLabel: true }
    ]
  }
)
const dragStartIndex = ref('')
const dragStartData = ref('')
const dragOverIndex = ref('')
// 拖动列表
const dragStart = (item, index) => {
  dragStartIndex.value = index
  dragStartData.value = item
}
// 鼠标指针进入放置区域才触发
const dragOver = (index) => {
  dragOverIndex.value = index
}
const dragEnd = () => {
  console.log('fangri')
  const copyTodolist = [...todolist.value.names]
  // 删除老的节点
  copyTodolist.splice(dragStartIndex.value, 1)
  // 在列表中目标位置增加新的节点
  copyTodolist.splice(dragOverIndex.value, 0, dragStartData.value)
  todolist.value.names = [...copyTodolist]
  dragOverIndex.value = ''
}

const dropArea = ref()
const tableDrop = ref()
// const allowDrop = () => {
//   console.log('dragOverIndex.value')
// }
const tableDivContent = ref([])
const offsetX = ref('')
const offsetY = ref('')
const tableX = ref('')
const tableY = ref('')
// 创建页面模板
const dropItem = (event) => {
  if (event) {
    if (dragStartData.value.barCodeLabel) {
      console.log('11234234', dragStartData.value)
      const rect = dropArea.value.getBoundingClientRect()
      tableX.value = event.clientX - rect.left
      tableY.value = event.clientY - rect.top
      if (tableDivContent.value.length > 0) {
        // for (let index = 0; index < tableDivContent.value.length; index++) {
        tableDivContent.value.forEach(element => {
          console.log('element')
          console.log(tableDivContent.value)
          console.log(element.id !== dragStartData.value.id)
          // if (element.id !== dragStartData.value.id) {
          tableDivContent.value.push(dragStartData.value)
          // 使用 reduce 方法进行去重
          let uniqueObjects = tableDivContent.value.reduce((acc, obj) => {
            // 使用一个临时对象的属性作为键，存储第一次出现的对象
            acc[obj.id] = acc[obj.id] || obj
            return acc
          }, {})

          // 将结果转换回数组形式
          uniqueObjects = Object.values(uniqueObjects)
          tableDivContent.value = uniqueObjects
          console.log('uniqueObjects')
          console.log(uniqueObjects)
          // }
        })
        // if (dragStartData.value.id !== tableDivContent.value[index].id) {
        //   console.log('dragStartData.value.id,tableDivContent.value[index]')
        //   console.log(dragStartData.value.id, tableDivContent.value[index])
        //
        // }
        // }
      } else {
        tableDivContent.value.push(dragStartData.value)
      }
      return
    }
    // 位置
    const rect = dropArea.value.getBoundingClientRect()
    offsetX.value = event.clientX - rect.left
    offsetY.value = event.clientY - rect.top
    todolist.value.names.forEach(element => {
      // 删除同名元素
      const existingElement = dropArea.value.querySelector(`.${dragStartData.value.name}`)
      console.log('name')
      console.log(existingElement)
      if (existingElement) {
        dropArea.value.removeChild(existingElement)
      }
      // 创建新的元素
      // newElement.setAttribute('img', 'myValue'); 添加属性
      const newElement = document.createElement('span')
      newElement.style.width = (dragStartData.value.width * 4.68) + 'px'
      newElement.style.height = (dragStartData.value.height * 4.68) + 'px'
      newElement.style.backgroundColor = 'red'
      newElement.style.display = 'inline-block'
      newElement.className = dragStartData.value.name
      newElement.innerHTML = dragStartData.value.label
      newElement.style.position = 'absolute'
      newElement.style.top = offsetY.value + 'px'
      newElement.style.left = offsetX.value + 'px'
      // newElement.addEventListener('dragstart', dragStart())
      // 添加删除
      newElement.addEventListener('contextmenu', function (event) {
        event.preventDefault()
        removeDom(newElement)
      })
      dropArea.value.appendChild(newElement)
      console.log(dropArea.value)
      // }
    })
  } else {
    todolist.value.names.forEach(element => {
      if (element.isOr) {
        if (element.barCodeLabel) {
          tableDivContent.value.push(element)
        } else {
          const existingElement = dropArea.value.querySelector(`.${element.name}`)
          console.log('names')
          console.log(existingElement)
          if (existingElement) return
          // 创建新的元素
          // newElement.setAttribute('img', 'myValue'); 添加属性
          const newElement = document.createElement('span')
          newElement.style.width = (element.width * 4.68) + 'px'
          newElement.style.height = (element.height * 4.68) + 'px'
          newElement.style.backgroundColor = 'red'
          newElement.style.display = 'inline-block'
          newElement.className = element.name
          newElement.innerHTML = element.label
          newElement.style.position = 'absolute'
          newElement.style.top = (element.top * 4.68) + 'px'
          newElement.style.left = (element.left * 4.68) + 'px'
          // newElement.addEventListener('contextmenu', removeDom(newElement))
          newElement.addEventListener('contextmenu', function (event) {
            event.preventDefault()
            removeDom(newElement)
          })
          dropArea.value.appendChild(newElement)
          console.log(dropArea.value)
        }
      }
    })
  }
}
// 右击删除
const removeDom = (newElement) => {
  console.log(newElement)
  console.log('name')
  console.log(newElement)
  todolist.value.names.forEach(e => {
    if (newElement.className === e.name) {
      dropArea.value.removeChild(newElement)
      e.isOr = false
    }
  })
}
// 创建模板
const heads = ref('<?xml version="1.0" encoding="UTF-8"?>\n')
const canshuArr = ref('')
// const templateCreate = ref(`
// <page
//         xmlns="http://cloudprint.cainiao.com/print"
//         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
//         xsi:schemaLocation="http://cloudprint.cainiao.com/print http://cloudprint-docs-resource.oss-cn-shanghai.aliyuncs.com/lpml_schema.xsd"
//         xmlns:editor="http://cloudprint.cainiao.com/schema/editor"
//         width="${todolist.value.widthPx}" height="${todolist.value.heightPx}"   splitable="true">\n
//  `)
const nextTemplate = ref('')
const TemplateContent = ref('')
const sets = () => {
  TemplateContent.value = ''
  TemplateContent.value += `<page
        xmlns="http://cloudprint.cainiao.com/print"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://cloudprint.cainiao.com/print http://cloudprint-docs-resource.oss-cn-shanghai.aliyuncs.com/lpml_schema.xsd"
        xmlns:editor="http://cloudprint.cainiao.com/schema/editor"
        width="${todolist.value.widthPx}" height="${todolist.value.heightPx}"   splitable="true">\n`
  canshuArr.value = ''
  const a = document.querySelector('#drop')
  console.log('a')
  console.log(a.children)
  for (let index = 0; index < a.children.length; index++) {
    const leftPx = a.children[index].style.left.replace(/px/g, '')
    const topPx = a.children[index].style.top.replace(/px/g, '')
    // const widthCode = a.children[index].style.width.replace(/px/g, '')
    // const heightCode = a.children[index].style.height.replace(/px/g, '')
    todolist.value.names.forEach(e => {
      if (a.children[index].className === e.name) {
        // if (e.barCodeLabel) {
        canshuArr.value += `var ${a.children[index].className} = _data.${a.children[index].className}\n`
        TemplateContent.value += `  <layout width="38" height="20" left="${Number(leftPx) / 4.68}" top="${Number(topPx) / 4.68}" style="zIndex:999999">
    <barcode  width="38" type="code128" ratioMode="ignoreRatio" style="hideText:false;rotation:0;">
      <![CDATA[<%=${a.children[index].className}%>]]>
    </barcode>
   </layout>\n`
        // }
        //  else {
        //         TemplateContent.value += `<layout width="${todolist.value.widthPx}" orientation="vertical" left="${Number(leftPx) / 4.68}" top="${Number(topPx) / 4.68}"  style="zIndex:3;">
        //             <text
        //                 style="fontFamily:SimHei;fontSize:12;">
        //                 <![CDATA[<%=${a.children[index].className}%>]]>
        //             </text>
        // </layout>\n`
        //       }
        e.top = Number(topPx) / 4.68
        e.left = Number(leftPx) / 4.68
        e.isOr = true
      }
    })
    TemplateContent.value = TemplateContent.value.replace(/<\/page>/g, '')
  }
  canshuArr.value += 'var skuInfo = _data.skuInfo\n'
  TemplateContent.value += `<layout width="${todolist.value.widthPx}" left="${tableX.value / 4.68}" top="${tableY.value / 4.68}" orientation="vertical" style="zIndex:999999;">
    <table width="150">  
    <tr >`
  tableDivContent.value.forEach(e => {
    TemplateContent.value += `
                              <th > 
                                    <text  style="align:center;vertical-align: middle">
                                            ${e.label}         
                                    </text>
                               </th>
                      
   `
    e.isOr = true
  })
  TemplateContent.value += '  </tr>\n'
  TemplateContent.value += '   <% for(i=0;i<skuInfo.length;i++) { %>\n<tr>'
  tableDivContent.value.forEach(e => {
    TemplateContent.value += ` 
              <td>
              <text   style="align:center;vertical-align: middle">
                      <![CDATA[<%=skuInfo[i].${e.name}%>]]>
                </text>
              </td>
          `
  })
  TemplateContent.value += `  </tr>
      <%}%>
     </table>
  </layout>`
  TemplateContent.value += '</page>'

  nextTemplate.value = heads.value + `<%
${canshuArr.value}
%>\n` + TemplateContent.value
  // console.log('JSON.stringify(todolist.value.names)')
  // console.log(todolist.value)
  console.log(+'1231231')
  console.log(nextTemplate.value)
  sysPrintTemplateSetUpdate({
    orderId: orderId.value,
    wide: todolist.value.widthPx,
    tableLeft: tableX.value,
    tableTop: tableY.value,
    high: todolist.value.heightPx,
    labelJson: JSON.stringify(todolist.value.names),
    isLock: todolist.value.checked1 ? 1 : 0,
    printTemplate: nextTemplate.value
  }).then(res => {
    ElMessage.success('保存成功')
    getDetile(route.query.ID)
  })
}

const tableContent = (item, index) => {
  console.log('item')
  console.log(item)
}
</script>

<style lang='less' scoped>
.draggable {
  position: absolute;
  width: 100px;
  height: 100px;
  cursor: pointer;
  background-color: #3498db;
  color: white;
  padding: 20px;
  border-radius: 10px;
  user-select: none;
  transition: all 0.2s;
}

.form {
  display: flex;
  align-items: center;
}

.list {
  list-style: none;

  .drag-move {
    transition: transform 0.3s;
  }

  .list-item {
    position: relative;
    cursor: move;
    width: 100px;
    background: #EA6E59;
    border-radius: 4px;
    color: #FFF;
    margin: 10px 20px;
    height: 50px;
    line-height: 50px;
    text-align: center;
  }
}

.list-item .is-dragover::before {
  content: "";
  position: absolute;
  bottom: -8px;
  left: 0;
  width: 100%;
  height: 4px;
  background-color: #0c6bc9;
}

.list-item.is-dragover::after {
  content: "";
  position: absolute;
  bottom: -12px;
  left: -6px;
  border: 3px solid #0c6bc9;
  border-radius: 50%;
  width: 6px;
  height: 6px;
  background-color: #fff;
}

.listssss {
  width: 100px;
  background: #EA6E59;
  border-radius: 4px;
  color: #FFF;
  margin: 10px 20px;
  height: 50px;
  line-height: 50px;
  text-align: center;

}

.one {
  display: flex;
  align-items: flex-start
}

table {
  border: 1px solid black;
  /* 添加表格整体的边框 */
  border-collapse: collapse;
  margin-bottom: 20px;
}

th,
td {
  border: 1px solid black;
  /* 单元格边框 */
  padding: 8px;
  text-align: left;
}

th {
  background-color: #f2f2f2;
}
</style>
